package cn.wolfcode.mq.listener;

import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.service.IOrderInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;

@RocketMQTransactionListener(txProducerGroup = MQConstant.INTEGRAL_REFUND_TX_GROUP)
@Component
@Slf4j
public class IntegralRefundLocalTransactionListener implements RocketMQLocalTransactionListener {

    @Autowired
    private IOrderInfoService orderInfoService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        log.info("[积分退款] 开始执行本地事务：{}", arg);
        try {
            // ③ 执行本地事务
            String orderNo = (String) arg;
            orderInfoService.commitRefund(orderNo);
        } catch (Exception e) {
            log.error("[积分退款] 执行本地事务失败：orderNo={}, err={}", arg, e.getMessage());
            return RocketMQLocalTransactionState.ROLLBACK;
        }

        log.info("[积分退款] 执行本地事务成功...");
        return RocketMQLocalTransactionState.COMMIT;
        // return RocketMQLocalTransactionState.UNKNOWN;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        MessageHeaders headers = msg.getHeaders();
        Object orderNo = headers.get("orderNo");
        log.info("[积分退款] 未收到本地事务执行结果，开始检查本地事务执行状态：{}", orderNo);
        // ⑤ 回查本地事务执行状态
        OrderInfo orderInfo = orderInfoService.findById((String) orderNo);
        // 如果查不到数据，或者状态不是已退款，说明本地事务执行失败了，回滚消息
        if (orderInfo == null || !OrderInfo.STATUS_REFUND.equals(orderInfo.getStatus())) {
            log.warn("[积分退款] 订单状态异常，回滚消息：orderNo={}, status={}", orderNo, orderInfo == null ? null : orderInfo.getStatus());
            return RocketMQLocalTransactionState.ROLLBACK;
        }

        log.info("[积分退款] 回查事务状态成功，本地事务已执行 {}", orderNo);
        return RocketMQLocalTransactionState.COMMIT;
    }
}
